from fastapi import FastAPI, Request
import requests
from fastapi.exceptions import RequestValidationError
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import JSONResponse
from pydantic import BaseModel


# 定义一个数据模型
class BaiDuAuthorizeItem(BaseModel):
    user_id: str
    code: str = None


app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],  # 允许的源列表，这里以 React 默认端口为例
    allow_credentials=True,
    allow_methods=["*"],  # 允许的方法列表
    allow_headers=["*"],  # 允许的头列表
)

# 百度网盘的配置信息
AppID = '44925431'
AppKey = "094gC8iu8GzfKk3blzHrVeexvCcaYsQ3"
CLIENT_SECRET = 'npqaGF5aYl7Seb1Wh4Z2Rvg25xYgkS2C'
REDIRECT_URI = 'oob'
TOKEN_URL = 'https://openapi.baidu.com/oauth/2.0/token'

access_token = "121.aeeb42636db5bd8a2629a6fce920c5f2.YgkE9XkHEdEQ4U4mhIRn8PP1QmKkQO9KAZxbnKD.gXGOxQ"

refresh_token = "122.7d20c581bf96fcbb451fb831775f27c7.YmunjsGekDazfEVmbqKtV3JH_czH5ZwGjxET2Zp.soUf3A"


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    errors = []
    for error in exc.errors():
        try:
            field = error['loc'][-1]  # 只获取字段名
            msg = error['msg']
            errors.append(f"{field}: {msg}")
        except Exception as e:
            pass
    detail = "Validation Error"
    if len(errors) > 0:
        detail = errors[0]
    return JSONResponse(
        status_code=422,
        content=detail
    )


@app.get("/v1/authorize_config")
async def get_authorize_config():
    return {
        "code": 0,
        "msg": "success",
        "data": "http://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id"
                "={}&redirect_uri=oob&scope=basic,netdisk".format(AppKey)
    }


@app.post("/v1/authorize_bd/{user_id}")
async def get_authorize_bd(user_id: str, code: str):
    payload = {
        'grant_type': 'authorization_code',
        'code': code,
        'client_id': AppKey,
        'client_secret': CLIENT_SECRET,
        'redirect_uri': REDIRECT_URI
    }
    response = requests.post(TOKEN_URL, data=payload)
    json_data = response.json()
    return {
        "code": 0,
        "msg": "success",
        "data": json_data
    }

# @app.get("")
